'use strict';
/**
 * 莫凡服务端中间键：后端加密操作，暂时忽略前端部分路由
 * @version 1.0.0
 * @author hxx xiech
 */

const CryptoJS = require("crypto-js");
const uuid = require("uuid");

module.exports = () => {
	return async function(ctx, next) {
		await next();
		let reobj = JSON.parse(ctx.body);
		// 判断是正常返回进行加密，否则不加密
		if (!reobj.errCode) {
			Object.assign(reobj, encryptData(reobj.data));
			ctx.body = JSON.stringify(reobj);
		}
	};
};


/*
 *	加密函数
 *
 * baseStr 需要加密的数据
 */
function encryptData(baseStr) {
	let mfrequesttime = new Date().getTime();
	// let request_id = uuid.v4();
	let _pubKey = uuid.v4();
	let key = CryptoJS.enc.Utf8.parse(_pubKey); //16位
	let iv = CryptoJS.enc.Utf8.parse(_pubKey);
	let encrypted = '';
	if (typeof(baseStr) == 'string') {
		let srcs = CryptoJS.enc.Utf8.parse(baseStr);
		encrypted = CryptoJS.AES.encrypt(srcs, key, {
			iv: iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
	} else if (typeof(baseStr) == 'object') { //对象格式的转成json字符串
		let data = JSON.stringify(baseStr);
		var srcs = CryptoJS.enc.Utf8.parse(data);
		encrypted = CryptoJS.AES.encrypt(srcs, key, {
			iv: iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		})
	}
	return {
		mfrequesttime: mfrequesttime,
		mfrequestid: _pubKey,
		data: encrypted.ciphertext.toString()
	}
}